<?php

namespace App\Services;

use App\Models\RsMsginfo;
use App\Models\RsReport;
use App\Models\ReportWork;
use App\Models\BpmMaindata;
use App\Models\RsReportAuth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class IndexService extends BaseService
{
    /**
     * 报工管理
     * @return array
     */
    public function reportManage() : array
    {
        return [
            'report'   => $this->myReport(),
            'approval' => $this->reportApproval()
        ];
    }

    /**
     * 我的报工
     * @return array
     */
    public function myReport(): array
    {
        try{
            return ReportWork::where('user_id',auth('api')->user()->id)
                ->where('is_deleted',0)
                ->orderBy('report_date','desc')
                ->limit(3)
                ->get()
                ->map(function ($item){
                    return [
                        'id'           => $item['report_uid'],
                        'title'        => $item['title'],
                        'project_name' => $item['project_name'],
                        'report_date'  => $item['report_date'],
                        'is_plan'      => $item['is_plan'],
                        'time'         => $item['standard_hours']
                            + $item['common_overtime_hours']
                            + $item['holiday_hours']
                            + $item['other_hours']
                            . 'h'
                    ];
                })
                ->toArray();
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('我的报工异常：'.$exception->getMessage());

            report($exception);

            return [];
        }
    }

    /**
     * 我的审批
     * @return array
     */
    public function reportApproval(): array
    {
        try{
            return ReportWork::where('user_id',auth('api')->user()->id)
                ->where('status_id',2)
                ->where('is_deleted',0)
                ->with([
                    'approver' => function($query){
                        return $query->with('person');
                    }
                ])
                ->whereExists(function ($query){
                    return $query->select(DB::raw(1))
                        ->from('r_user_projectauth')
                        ->where('r_user_projectauth.operation_id',190)
                        ->whereRaw('r_user_projectauth.project_id = report_work.project_id')
                        ->where('r_user_projectauth.user_id',auth('api')->user()->id);
                })
                ->orderBy('report_date','desc')
                ->whereNull('approver_time')
                ->limit(3)
                ->get()
                ->map(function ($item){
                    return [
                        'id'           => $item['report_uid'],
                        'project_name' => $item['project_name'],
                        'title'        => $item['title'],
                        'report_date'  => $item['report_date'],
                        'time'         => $item['standard_hours']
                            + $item['common_overtime_hours']
                            + $item['holiday_hours']
                            + $item['other_hours']
                            . 'h',
                        'name'    => $item['approver']['person']['name'] ?? '',
                        'status'  => $item['status_id'],
                        'is_plan' => $item['is_plan'],
                    ];
                })
                ->toArray();
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('报工审批异常：'.$exception->getMessage());

            report($exception);

            return [];
        }
    }

    public function getTables() : array
    {
//        return RsReport::where('is_show_home',1)
//            ->leftJoin('rs_report_auth',function ($join){
//                return $join->on('rs_report_auth.report_id','=','rs_report.id')
//                    ->where('rs_report_auth.user_id',auth('api')->user()->id);
//            })
//            ->select([
//                'rs_report.id',
//                'rs_report.report_name',
//                'rs_report_auth.id as status'
//            ])
//            ->get()
//            ->map(function ($item){
//                return [
//                    'id'     => $item->id,
//                    'name'   => $item->report_name,
//                    'status' => !is_null($item->status)
//                ];
//            })
//            ->toArray();
        return RsReportAuth::with([
                'report' => function($query){
                    return $query->where('is_show_home',1);
                }
            ])
            ->where('user_id',auth('api')->user()->id)
            ->get()
            ->map(function ($item){
                if (isset($item->report->id,$item->report->report_name) && !empty($item->report->id) && !empty($item->report->report_name)){
                    return [
                        'id'        => $item->report->id,
                        'name'      => $item->report->report_name,
                        'status'    => !is_null($item->id)
                    ];
                }
            })
            ->toArray();
    }

    /**
     * 获取到查询数据
     * @param array $parameters
     * @return array
     */
    public function search(array $parameters) : array
    {
        if (empty($parameters['search'])) {
            return customer_return_success('success',[]);
        }

        switch ($parameters['type']) {
            case 1:
                $data = $this->getSearchAllTypeData($parameters['search']);
                break;
            case 2:
                $data = $this->getSearchServiceData($parameters['search']);
                break;
            case 3:
                $data = $this->getSearchReportData($parameters['search']);
                break;
            default;
                $data = $this->getSearchMessageData($parameters['search']);
        }

        return customer_return_success('success',$data);
    }

    /**
     * 获取到报工和服务单数据
     * 报工的数据分成2种
     * 一种是
     * @param string $search
     * @return array
     */
    public function getSearchAllTypeData(string $search) : array
    {
        $data = [];

        $report = ReportWork::where('user_id',auth('api')->user()->id)
            ->where(function($query) use ($search) {
                return $query->where('project_name','like','%'.$search.'%')
                    ->orWhere('title','like','%'.$search.'%');
            })
            ->where('is_deleted',0)
            ->orderBy('report_date','desc')
            ->get()
            ->map(function ($item){
                return [
                    'id'           => $item['report_uid'],
                    'project_name' => $item['project_name'],
                    'title'        => $item['title'],
                    'report_date'  => $item['report_date'],
                    'time'         => $item['standard_hours']
                        + $item['common_overtime_hours']
                        + $item['holiday_hours']
                        + $item['other_hours']
                        . 'h',
                    'status'  => $item['status_id'],
                    'is_plan' => $item['is_plan'],
                    'message' => '报工数据'
                ];
            })
            ->toArray();

        $service =  BpmMaindata::where('WF_AddName',auth('api')->user()->username)
            ->where(function ($query) use ($search){
                return $query->where('Subject','like','%'.$search.'%')
                    ->orWhere('WF_ProcessName','like','%'.$search.'%');
            })
            ->select([
                'WF_OrUnid',
                'Subject',
                'WF_ProcessName',
                'WF_DocCreated'
            ])
            ->orderBy('WF_DocCreated','desc')
            ->get()
            ->map(function ($item){
                return [
                    'id'      => $item['WF_OrUnid'],
                    'subject' => $item['Subject'],
                    'title'   => $item['WF_ProcessName'],
                    'date'    => date('Y-m-d',strtotime($item['WF_DocCreated'])),
                    'message' => '服务单数据'
                ];
            })
            ->toArray();

        if (!empty($report)) {
            $data['report'] = $report;
        }

        if (!empty($service)) {
            $data['service'] = $service;
        }

        //查询消息数据
        $res=$this->getSearchMessageData($search);
        if(!empty($res)){
            $data['msg']=$res;
        }
        return $data;
    }

    public function getSearchServiceData(string $search) : array
    {
        return BpmMaindata::where('WF_AddName',auth('api')->user()->username)
            ->where(function ($query) use ($search){
                return $query->where('Subject','like','%'.$search.'%')
                    ->orWhere('WF_ProcessName','like','%'.$search.'%');
            })
            ->select([
                'WF_OrUnid',
                'Subject',
                'WF_ProcessName',
                'WF_DocCreated'
            ])
            ->orderBy('WF_DocCreated','desc')
            ->get()
            ->map(function ($item){
                return [
                    'id'      => $item['WF_OrUnid'],
                    'subject' => $item['Subject'],
                    'title'   => $item['WF_ProcessName'],
                    'date'    => date('Y-m-d',strtotime($item['WF_DocCreated']))
                ];
            })
            ->toArray();
    }

    public function getSearchReportData(string $search) : array
    {
        return ReportWork::where('user_id',auth('api')->user()->id)
            ->where('is_deleted',0)
            ->where(function($query) use ($search) {
                return $query->where('project_name','like','%'.$search.'%')
                    ->orWhere('title','like','%'.$search.'%');
            })
            ->orderBy('report_date','desc')
            ->get()
            ->map(function ($item){
                return [
                    'id'           => $item['report_uid'],
                    'project_name' => $item['project_name'],
                    'title'        => $item['title'],
                    'report_date'  => $item['report_date'],
                    'time'         => $item['standard_hours']
                        + $item['common_overtime_hours']
                        + $item['holiday_hours']
                        + $item['other_hours']
                        . 'h',
                    'status'  => $item['status_id'],
                    'is_plan' => $item['is_plan'],
                ];
            })
            ->toArray();
    }

    public function getSearchMessageData(string $search) : array
    {
        //查询当前消息数据
        $res=RsMsginfo::with(['getRsManage.id,msg_group,msg_type','getRecevier.id,username','getSend.id,username'])
            ->where('msg_title','like','%'.$search.'%')
            ->where('recevier_id','=',auth('api')->user()->id)
            ->get()
            ->toArray();
        return $res;
    }
}
